package com.work.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JdbcUtils {
	//获取数据库连接池
	private static DataSource ds;

	//提供静态代码块
	//加载配置文件
	static{
		try{
			//创建Properties集合类对象
			Properties prop = new Properties();
			//加载配置文件
			InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
			//加载
			prop.load(inputStream);
			inputStream.close();
			//创建连接池对象
			ds = DruidDataSourceFactory.createDataSource(prop);
		} catch(IOException e){
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	//获取连接
	public static Connection getConnection() throws SQLException {
		return ds.getConnection() ;
	}

	//定义一个方法,获取存在的连接池
	public static DataSource getDataSource() {
		return ds ;
	}

	//释放资源
	public static void close(Statement stmt, Connection conn) {

		close(null,stmt,conn) ;
	}

	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if(stmt!=null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if(conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}